﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Collections.Specialized;
using System.Web;

namespace SmartVault.Net.Http
{
    public class WebRequestInfo
    {
        private Uri Uri;
        private string Username;
        private string Password;
        private string Authentication;
        public MediaType MediaType { get; private set; }
        public Encoding Encoding { get; private set; }

        /// <summary>
        /// Constructs a NameValueCollection into a query string.
        /// </summary>
        /// <remarks>Consider this method to be the opposite of "System.Web.HttpUtility.ParseQueryString"</remarks>
        /// <param name="parameters">The NameValueCollection</param>
        /// <param name="delimiter">The String to delimit the key/value pairs</param>
        /// <returns>A key/value structured query string, delimited by the specified String</returns>
        public static String ConstructQueryString(NameValueCollection parameters, String delimiter, Boolean omitEmpty)
        {
            if (parameters == null || parameters.Count == 0) return string.Empty;

            if (String.IsNullOrEmpty(delimiter))
                delimiter = "&";

            Char equals = '=';
            List<String> items = new List<String>();

            for (int i = 0; i < parameters.Count; i++)
            {
                foreach (String value in parameters.GetValues(i))
                {
                    Boolean addValue = (omitEmpty) ? !String.IsNullOrEmpty(value) : true;
                    if (addValue)
                        items.Add(String.Concat(parameters.GetKey(i), equals, HttpUtility.UrlEncode(value)));
                }
            }

            return String.Join(delimiter, items.ToArray());
        }

        public WebRequestInfo(Uri uri, string username, string password, MediaType mediaType, Encoding encoding)
        {
            this.Uri = uri;
            this.Username = username;
            this.Password = password;
            this.MediaType = mediaType;
            this.Encoding = encoding;

            if (!string.IsNullOrEmpty(this.Username))
            {
                string cre = String.Format("{0}:{1}", this.Username, this.Password);
                byte[] bytes = Encoding.ASCII.GetBytes(cre);
                string base64 = Convert.ToBase64String(bytes);

                this.Authentication = "Basic " + base64;
            }
        }

        public WebRequestInfo BrowseTo(string path, NameValueCollection collection)
        {
            path = path.Replace("#", "%23");

            //path = HttpUtility.UrlPathEncode(path);


            string tmp = ConstructQueryString(collection, "", true);
            if (!string.IsNullOrEmpty(tmp)) tmp = "?" + tmp;

            Uri uri = new Uri(Uri, path + tmp);

            return new WebRequestInfo(uri, this.Username, this.Password, this.MediaType, this.Encoding);
        }

        public ClientContext CreateContext(HttpMethods method)
        {
            HttpWebRequest rqst = CreateRequest();
            ClientReader rdr = new ClientReader(rqst);
            ClientWriter wrt = new ClientWriter(rqst);

            ClientContext context = new ClientContext(rdr, wrt);

            if (!method.Equals(HttpMethods.GET))
            {
                context.Writer.HttpMethod = method;
            }

            return context;
        }

        private HttpWebRequest CreateRequest()
        {
            HttpWebRequest request = (HttpWebRequest)
                WebRequest.Create(this.Uri);

            if (!string.IsNullOrEmpty(this.Authentication))
            {
                request.Headers.Add("Authorization", this.Authentication);
            }
            return request;
        }
    }
}
